var chathandle = {};

google.setOnLoadCallback(function() {
	$('.slideshow').cycle({
		fx:     'fade', 
		speed:  800, 
		timeout: 5000, 
		next:   '.right_arrow', 
		prev:   '.left_arrow' 
	});
	
	//comet.open(BASE_URI+'index2.php', push, disconnected);
	//setInterval("readCookie()",1000);
	$("#currency ul li").each(function(i,o){
		$(this).hide().addClass('hid');
	});
	$("#currency ul li.current").show();
	$("#currency").live('click',function(){
		if($("#currency ul li").hasClass('hid')){
			$("#currency ul li").show().removeClass('hid');
		}else{
			$("#currency ul li").hide().addClass('hid');
			$("#currency ul li.current").show();
		}	
	});
	
	$('#tournament-show-div a').live('click',function(){
		$link = $(this).attr('href');
		$.get($link,{},function(res){
			$('#tournament-show-div').html(res);
		});
		return false;
	});
	
	$('.item_direct_bet_place_manual').live('click',function(){
		var eid = $(this).attr('rel');
		$(this).place_direct_bet_manual(eid);
	}); 
	
	$('.from_range_manual').live('keyup',function(){
		$(this).calculateRangeDenote($(this).attr('rel'),$(this).attr('value'));
	});
	$('.input_box_manual').live('keyup',function(){
		$(this).attr( 'value', $(this).val() );
		$(this).storeValueInputBoxes($(this).attr('rel'),$(this).attr('value'));
	});
	
	
	$('#prize-tab .tab').bind('click',function(){
		$task = $(this).attr('rel');
		$tid = $('#tournament-show-div').attr('rel');
		if($task == 'weekly'){
			$('#rank_title_div').removeClass('title').removeClass('title2').addClass('title');
		}else{
			$('#rank_title_div').removeClass('title').removeClass('title2').addClass('title2');
		}
		if($(this).hasClass('act')){
			return false;
		}
		$curId = $('#prize-tab .act').attr('id'); 
		$id = $(this).attr('id');
		$('#content-tab .'+$id).fadeIn();
		$('#content-tab .'+$curId).fadeOut();
		$('#prize-tab .tab').removeClass('act');
		$(this).addClass('act');
		$('#tournament-show-div').fadeOut();
		$.get(BASE_URI+MODULE+'/contentload/change_top_rank',{type:$task,tid:$tid},function(res){
			$('#tournament-show-div').html(res).fadeIn();
		});
	});
});

function doReload(){
	if(LOGIN_OPEN == '0'){
		reload();
	}
}

function doRefresh(mid){
	if(!mid){reload();}
	$('.refresh_button').text('Refreshing...');
	$.get(BASE_URI+MODULE+'/async/updateScore',{mid:mid},function(res){
		reload();
	});
}

function dochange_DDvaluebet($value, $id){
	$('#direct_stake_'+$id+" option").attr('selected',false);
	$('#direct_stake_'+$id+" option[value='"+$value+"']").attr('selected','selected');
	$(this).calculateWinPointsGet_direct($id,$value);
}

google.setOnLoadCallback(function() {
	//$('.refresh_button').click(function(){reload();});
	$('#_signin').click(function(){/*$('#header_login').show();LOGIN_OPEN = '1';*/ queryURL(BASE_URI+MODULE+'/user/user_login');});
	$('#closed').live('click',function(){$('#header_login').hide();LOGIN_OPEN = '0';});
	$('#_register').click(function(){queryURL(BASE_URI+MODULE+'/user/register');});
	$('#_logout').click(function(){queryURL(BASE_URI+MODULE+'/user/logout');});
	//$('#forgot_details').click(function(){queryURL(BASE_URI+MODULE+'/user/forgot_details');});
	$('#submit_login').live('click',function(){
		$(this).login();
	}); 
	
	$('.countdown').each(function(i,o){
		var id = $(this).attr('id');
		var time = $(this).attr('rel');
		if($(this).hasClass('lower')){
			var format = "lower";
		}else{
			var format = "upper";
		}
		$('#'+id).countdown(id,time,format);
	});
	
	$('.collapse').live('click',function(){
		var div = $(this).attr('rel');
		$(this).divtoggle(div);
	});
	$('.item_direct_bet_add_betslip').live('click',function(){
		var eid = $(this).attr('rel');
		$(this).clickbet(eid);
	});
	$('.clickbet').live('click',function(){
		var eid = $(this).attr('rel');
		$(this).click2open(eid);
	});
	$('.direct_bet').live('click',function(){return false;});
	
	$('.item_direct_bet_grid_close').live('click',function(){ 
		var eid = $(this).attr('rel');
		$('#direct_bet_'+eid).addClass('hidden');
		opening_event.id = 0;
		return false;
	});
	$('.item_bet_grid_delete').live('click',function(){
		var eid = $(this).attr('rel');
		$(this).deletebet(eid);
	});
	$('#remove_bet').live('click',function(){
		$('.itembet').remove();
	});
	
	$('#_submit').click(function(){
		$('form#convert_submit').submit();
	});
	
	$('.item_direct_bet_place').live('click',function(){
		var eid = $(this).attr('rel');
		$(this).place_direct_bet(eid);
	}); 
	$('.setoddsinput').live('keyup',function(){
		$(this).calculateWinPointsGet($(this).attr('rel'),$(this).attr('value'));
	});
	$('.direct_setoddsinput').live('keyup',function(){
		$(this).calculateWinPointsGet_direct($(this).attr('rel'),$(this).attr('value'));
	});
/*	$('.direct_setoddsslb').live('change',function(){
		$value = $(this).attr('value');
		$id = $(this).attr('rel');
		$('#direct_stake_'+$id+" option").attr('selected',false);
		$('#direct_stake_'+$id+" option[value='"+$value+"']").attr('selected','selected');
		$(this).calculateWinPointsGet_direct($(this).attr('rel'),$(this).attr('value'));
	});

	
	$('input#coint').live('keypress',function(){
		//return false;
	});
*/
	
	$('#point').focusin(
		function(){
			if($(this).val() == 'Points'){
				$(this).attr('value','');
			}
		}
	).focusout(
		function(){
			if($(this).val() == ''){
				$(this).attr('value','Points');
			}
		}
	);
	
	$('#point').live('keyup',function(){
		$(this).convertion('coin',$(this).attr('value'));
	})
	
	var optionsPlacebet = { 
		beforeSubmit:beforeSubmitBet,   
		success:afterSubmitBet
	};	
	var optionsConvertion = { 
		beforeSubmit:beforeSubmitConvertion,   
		success:afterSubmitConvertion
	};	
	
	jQuery("#placebet_submit").live("submit",function(e){
		e.preventDefault();
		if(PRE_QUESTION){
			jQuery('#hiddenElement').html(PRE_QUESTION);
			jQuery( "#hiddenElement" ).dialog({
				resizable: false,
				height:200,
				width: 350,
				//modal: true,
				buttons: {
					"Ok": function() {
						$( this ).dialog( "close" );
						jQuery("#placebet_submit").ajaxSubmit(optionsPlacebet);
					},
					Cancel: function() {
						$( this ).dialog( "close" );
						return false;
					}
				}
			});
	 	}else{
			jQuery(this).ajaxSubmit(optionsPlacebet);
		}
		
		return false;
	}); 
	
/*	$('#bet_submit').click(function(){
		$('form#placebet_submit').submit(function(){
			jQuery(this).ajaxForm(optionsPlacebet); 
		});
	});		
	jQuery('#placebet_submit').ajaxForm(optionsPlacebet); 
*/	
	jQuery("#convert_submit").live("submit",function(e){
		e.preventDefault();
		jQuery(this).ajaxSubmit(optionsConvertion);
		return false;
	});
});

function beforeSubmitConvertion(formData, jqForm, options){
	return true;
}

function afterSubmitConvertion(responseText, statusText, xhr, $form){
	var result = jQuery.parseJSON(responseText);
	if(result.status == 'ok'){
		$('#point').attr('value','point');
		$('#coin').attr('value','coin');
	}
	jQuery('#hiddenElement').html(result.msg);
	jQuery('#hiddenElement').dialog(
		{
			 width: 350,
			 resizable: false,
			 height:200 ,
			 beforeClose: function(event, ui) { 
				if(result.status == 'ok'){
					reload();
				}
			 },
       buttons: {
					"Ok": function() {
						$( this ).dialog( "close" );
				  }
      }  
			// title: '' 
		}
	);
}

function beforeSubmitBet(formData, jqForm, options){  
	return true;	
}

function afterSubmitBet(responseText, statusText, xhr, $form){
	var result = jQuery.parseJSON(responseText);
	if(result.status == 'ok'){
		$('.itembet').remove();	
	}
	jQuery('#hiddenElement').html(result.msg);
	jQuery('#hiddenElement').dialog(
		{
			 width: 350,
			 resizable: false,
			 height:200 ,
			 beforeClose: function(event, ui) { 
				if(result.status == 'ok'){
					reload();
				}
			 },
			  buttons: {
					"Ok": function() {
						$( this ).dialog( "close" );
					}
				}
			// title: '' 
		}
	);
}

function go_predict(tid,mid,scrid){
	queryURL(BASE_URI+MODULE+'/tournament/in_match/?tid='+tid+'&mid='+mid+'&scrid='+scrid);
} 

function go_predict_upcoming(tid,mid,scrid){
	queryURL(BASE_URI+MODULE+'/tournament/in_upcoming_match/?tid='+tid+'&mid='+mid+'&scrid='+scrid);
}

function go_predict_tournament(tid,scrid){
	queryURL(BASE_URI+MODULE+'/tournament/tournament_predictions/?tid='+tid+'&scrid='+scrid);
}

function view_full_scorecard(mid){
	/* $.get(BASE_URI+MODULE+'/contentload/view_full_scorecard',{mid:mid},function(res){
		jQuery('#hiddenElement').html(res);
		jQuery('#hiddenElement').dialog(
			{
				 width: 550,
				 resizable: false,
				 height:300 ,
				 beforeClose: function(event, ui) { 
				 },
				 buttons:{},
				 title: 'View Full Scorecard' 
			}
		);
	});
	*/
	queryURL(BASE_URI+MODULE+'/tournament/match_scorecard/?mid='+mid);
}

function push(event) {
	$.cookie('the_cookie_clicxa', '11');
	$.cookie('the_cookie_clicxa', event);
}

function disconnected(){}

function readCookie(){
	var php_js = new PHP_JS();
	if(isEmpty($.cookie('the_cookie_clicxa'))){return ;}
	return $.cookie('the_cookie_clicxa');
}

function getChatHandle(){
	var user = $('#clxUsername').val();
	$.get(BASE_URI+'chathandle2.php',{user:user},function(res){
		chathandle = res;
	},'json');
}

function showchatbar(){
	if(chathandle){
		if(chathandle.status == true){
			if(chathandle.pos == 'C_A'){
				$('#chatIFclx').height(370);
			}else if(chathandle.pos == 'C_B'){
				$('#chatIFclx').height(100);
			}else if(chathandle.pos == 'C_AB'){
				$('#chatIFclx').height(170);
			}else if(chathandle.pos == 'C_C'){
				$('#chatIFclx').height(40);
			}else{
				$('#chatIFclx').height(0);
			}
		}
	}
}

jQuery(document).ready(function() {
	 $("h2.expand").toggler({method: "toggle", speed: 80});
	 //window.setInterval('getChatHandle()',1000);
	 //window.setInterval('showchatbar()',800);
	 $('#clxchatpopup').popupWindow({  
			width:950, 
			top:50, 
			left:50 ,
			resizable:1, 
			scrollbars:1, 
			//status:1
		}); 
});



/* ---------------------------------------------
expandAll v.1.3.8.2
http://www.adipalaz.com/experiments/jquery/expand.html
Requires: jQuery v1.3+
Copyright (c) 2009 Adriana Palazova
Dual licensed under the MIT (http://www.adipalaz.com/docs/mit-license.txt) and GPL (http://www.adipalaz.com/docs/gpl-license.txt) licenses
------------------------------------------------ */
(function($) {
$.fn.expandAll = function(options) {
    var o = $.extend({}, $.fn.expandAll.defaults, options);   
    
    return this.each(function(index) {
        var $$ = $(this), $referent, $sw, $cllps, $tr, container, toggleTxt, toggleClass;
               
        // --- functions:
       (o.switchPosition == 'before') ? ($.fn.findSibling = $.fn.prev, $.fn.insrt = $.fn.before) : ($.fn.findSibling = $.fn.next, $.fn.insrt = $.fn.after);
                    
        // --- var container 
        if (this.id.length) { container = '#' + this.id;
        } else if (this.className.length) { container = this.tagName.toLowerCase() + '.' + this.className.split(' ').join('.');
        } else { container = this.tagName.toLowerCase();}
        
        // --- var $referent
        if (o.ref && $$.find(o.ref).length) {
          (o.switchPosition == 'before') ? $referent = $$.find("'" + o.ref + ":first'") : $referent = $$.find("'" + o.ref + ":last'");
        } else { return; }
        
        // end the script if the length of the collapsible element isn't long enough.  
        if (o.cllpsLength && $$.closest(container).find(o.cllpsEl).text().length < o.cllpsLength) {$$.closest(container).find(o.cllpsEl).addClass('dont_touch'); return;}
    
        // --- if expandAll() claims initial state = hidden:
        (o.initTxt == 'show') ? (toggleTxt = o.expTxt, toggleClass='') : (toggleTxt = o.cllpsTxt, toggleClass='open');
        if (o.state == 'hidden') { 
          $$.find(o.cllpsEl + ':not(.shown, .dont_touch)').hide().findSibling().find('> a.open').removeClass('open').data('state', 0); 
        } else {
          $$.find(o.cllpsEl).show().findSibling().find('> a').addClass('open').data('state', 1); 
        }
        
        (o.oneSwitch) ? ($referent.insrt('<p class="switch"><a href="#" class="' + toggleClass + '">' + toggleTxt + '</a></p>')) :
          ($referent.insrt('<p class="switch"><a href="#" class="">' + o.expTxt + '</a>&nbsp;|&nbsp;<a href="#" class="open">' + o.cllpsTxt + '</a></p>'));

        // --- var $sw, $cllps, $tr :
        $sw = $referent.findSibling('p').find('a');
        $cllps = $$.closest(container).find(o.cllpsEl).not('.dont_touch');
        $tr = (o.trigger) ? $$.closest(container).find(o.trigger + ' > a') : $$.closest(container).find('.expand > a');
                
        if (o.child) {
          $$.find(o.cllpsEl + '.shown').show().findSibling().find('> a').addClass('open').text(o.cllpsTxt);
          window.$vrbls = { kt1 : o.expTxt, kt2 : o.cllpsTxt };
        }

        var scrollElem;
        (typeof scrollableElement == 'function') ? (scrollElem = scrollableElement('html', 'body')) : (scrollElem = 'html, body');
        
        $sw.click(function() {
            var $switch = $(this),
                $c = $switch.closest(container).find(o.cllpsEl +':first'),
                cOffset = $c.offset().top - o.offset;
            if (o.parent) {
              var $swChildren = $switch.parent().nextAll().children('p.switch').find('a');
                  kidTxt1 = $vrbls.kt1, kidTxt2 = $vrbls.kt2,
                  kidTxt = ($switch.text() == o.expTxt) ? kidTxt2 : kidTxt1;
              $swChildren.text(kidTxt);
              if ($switch.text() == o.expTxt) {$swChildren.addClass('open');} else {$swChildren.removeClass('open');}
            }
            if ($switch.text() == o.expTxt) {
              if (o.oneSwitch) {$switch.text(o.cllpsTxt).attr('class', 'open');}
              $tr.addClass('open').data('state', 1);
              $cllps[o.showMethod](o.speed);
            } else {
              if (o.oneSwitch) {$switch.text(o.expTxt).attr('class', '');}
              $tr.removeClass('open').data('state', 0);
              if (o.speed == 0 || o.instantHide) {$cllps.hide();} else {$cllps[o.hideMethod](o.speed);}
              if (o.scroll && cOffset < $(window).scrollTop()) {$(scrollElem).animate({scrollTop: cOffset},600);}
          }
          return false;
        });
        /* -----------------------------------------------
        To save file size, feel free to remove the following code if you don't use the option: 'localLinks: true'
        -------------------------------------------------- */
        if (o.localLinks) { 
          var localLink = $(container).find(o.localLinks);
          if (localLink.length) {
            // based on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
            $(localLink).click(function() {
              var $target = $(this.hash);
              $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
              if ($target.length) {
                var tOffset = $target.offset().top;
                $(scrollElem).animate({scrollTop: tOffset},600);
                return false;
              }
            });
          }
        }
        /* -----------------------------------------------
        Feel free to remove the following function if you don't use the options: 'localLinks: true' or 'scroll: true'
        -------------------------------------------------- */
        //http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
        function scrollableElement(els) {
          for (var i = 0, argLength = arguments.length; i < argLength; i++) {
            var el = arguments[i],
                $scrollElement = $(el);
            if ($scrollElement.scrollTop() > 0) {
              return el;
            } else {
              $scrollElement.scrollTop(1);
              var isScrollable = $scrollElement.scrollTop() > 0;
              $scrollElement.scrollTop(0);
              if (isScrollable) {
                return el;
              }
            }
          };
          return [];
        }; 
      /* --- end of the optional code --- */
});};
$.fn.expandAll.defaults = {
        state : 'hidden', // If 'hidden', the collapsible elements are hidden by default, else they are expanded by default 
        initTxt : 'show', // 'show' - if the initial text of the switch is for expanding, 'hide' - if the initial text of the switch is for collapsing
        expTxt : '[Expand All]', // the text of the switch for expanding
        cllpsTxt : '[Collapse All]', // the text of the switch for collapsing
        oneSwitch : true, // true or false - whether both [Expand All] and [Collapse All] are shown, or they swap
        ref : '.expand', // the switch 'Expand All/Collapse All' is inserted in regards to the element specified by 'ref'
        switchPosition: 'before', //'before' or 'after' - specifies the position of the switch 'Expand All/Collapse All' - before or after the collapsible element
        scroll : false, // false or true. If true, the switch 'Expand All/Collapse All' will be dinamically repositioned to remain in view when the collapsible element closes
        offset : 20,
        showMethod : 'slideDown', // 'show', 'slideDown', 'fadeIn', or custom
        hideMethod : 'slideUp', // 'hide', 'slideUp', 'fadeOut', or custom
        speed : 600, // the speed of the animation in m.s. or 'slow', 'normal', 'fast'
        cllpsEl : '.collapse', // the collapsible element
        trigger : '.expand', // if expandAll() is used in conjunction with toggle() - the elements that contain the trigger of the toggle effect on the individual collapsible sections
        localLinks : null, // null or the selector of the same-page links to which we will apply a smooth-scroll function, e.g. 'a.to_top'
        parent : false, // true, false
        child : false, // true, false
        cllpsLength : null, //null, {Number}. If {Number} (e.g. cllpsLength: 200) - if the number of characters inside the "collapsible element" is less than the given {Number}, the element will be visible all the time
        instantHide : false // {true} fixes hiding content inside hidden elements
};

/* ---------------------------------------------
Toggler v.1.0
http://www.adipalaz.com/experiments/jquery/expand.html
Requires: jQuery v1.3+
Copyright (c) 2009 Adriana Palazova
Dual licensed under the MIT (http://www.adipalaz.com/docs/mit-license.txt) and GPL (http://www.adipalaz.com/docs/gpl-license.txt) licenses
------------------------------------------------ */
$.fn.toggler = function(options) {
    var o = $.extend({}, $.fn.toggler.defaults, options);
    
    var $this = $(this);
    $this.wrapInner('<a style="display:block" href="#" title="Expand/Collapse" />');
    if (o.initShow) {$(o.initShow).addClass('shown');}
    $this.next(o.cllpsEl + ':not(.shown)').hide();
    return this.each(function() {
      var container;
      (o.container) ? container = o.container : container = 'html';
      if ($this.next('div.shown').length) { $this.closest(container).find('.shown').show().prev().find('a').addClass('open'); }
      $(this).click(function() {
        $(this).find('a').toggleClass('open').end().next(o.cllpsEl)[o.method](o.speed);
        return false;
    });
});};
$.fn.toggler.defaults = {
     cllpsEl : 'div.collapse',
     method : 'slideToggle',
     speed : 'slow',
     container : '', //the common container of all groups with collapsible content (optional)
     initShow : '.shown' //the initially expanded sections (optional)
};
/* ---------------------------------------------
Feel free to remove any of the following functions if you don't need it.
------------------------------------------------ */
//credit: http://jquery.malsup.com/fadetest.html
$.fn.fadeToggle = function(speed, callback) {
    return this.animate({opacity: 'toggle'}, speed, function() { 
    if (jQuery.browser.msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
};
$.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, function() { 
    if (jQuery.browser.msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
};
$.fn.slideFadeDown = function(speed, callback) { 
  return this.animate({opacity: 'show', height: 'show'}, speed, function() { 
    if (jQuery.browser.msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
}; 
$.fn.slideFadeUp = function(speed, callback) { 
  return this.animate({opacity: 'hide', height: 'hide'}, speed, function() { 
    if (jQuery.browser.msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
}; 
/* --- end of the optional code --- */
})(jQuery);